// @flow
import React, { Component } from 'react'
import styles from './ModelItem.css'
import { Spin } from 'antd'

type Props = {
  data: Object,
  loading: boolean,
  imgUrl: string,
  match: Object,
  history: Object
}
type States = {
  imgUrl: string
}
class ModelItem extends Component {
  props: Props
  state: States
  createTask: Function
  imgError: Function
  detailLink: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      imgUrl: '/models/default.png'
    }
    this.detailLink = this.detailLink.bind(this)
    this.createTask = this.createTask.bind(this)
    this.imgError = this.imgError.bind(this)
  }
  componentDidMount () {
    // const owner = this.props.data.owner
    // if (owner.endsWith('.png')) {
    //   this.setState({
    //     imgUrl: `/models/${owner}`
    //   })
    // }
    this.setState({
      imgUrl: this.props.data.picUrl
    })
  }
  createTask () {
    const { history, data } = this.props
    history.push({
      pathname: '/analysis/task-add',
      state: {
        modelId: data.id
      }
    })
  }
  detailLink () {
    const { history, data, match } = this.props
    if (match.url === '/analysis/service') match.url = '/analysis'
    const detailLink = match.url.indexOf('analysis') > -1
      ? `${match.url}/models/${this.props.data.id}`
      : `models/${this.props.data.id}`
    const { imgUrl } = this.state
    data['imgUrl'] = imgUrl
    history.push({
      pathname: detailLink,
      state: {
        data: data
      }
    })
  }
  imgError () {
    this.setState({
      imgUrl: '/models/default.png'
    })
  }
  render () {
    const { imgUrl } = this.state
    return (
      <div className={`${styles['model-item']} animated fadeIn`}>
        <div className={styles['model-item-container']}>
          <Spin spinning={this.props.loading}>
            <div className={styles['model-img']}>
              <img src={imgUrl} onError={this.imgError} />
            </div>
            <div className={styles['model-content']}>
              <strong>{this.props.data.name}</strong>
              <div className={styles['model-item-container-text']}
                title={this.props.data.shortDesc}>
                {this.props.data.shortDesc}
              </div>
              <div className={styles['model-item-container-link']}>
                <a onClick={this.detailLink}>
                  模型详情
                </a>
                <a onClick={this.createTask} className={styles['linkRight']}>
                  创建任务
                </a>
              </div>
            </div>
          </Spin>
        </div>
      </div>
    )
  }
}

export default ModelItem
